package server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Player implements Runnable {
	private Socket sock;
	private final int playerID;
	private static int playerIDGen = 1;
	private boolean running;
	private Game game;
	// Message terminator
	private char EOF = (char) 0x00;
	PrintWriter data_out;

	public Player(Socket s) {
		playerID = playerIDGen++;
		System.out.println("Just received a connection!" + this.toString());
		sock = s;
		running = false;
		game = null;
	}

	public void run() {
		// listen to the socket, and destroy this object
		try {
			running = true;
			listen();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			running = false;
			try {
				sock.close();
				data_out.print("Welcome to the pente server chat room! Type /help for help." + EOF);
				data_out.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private void listen() throws IOException {
		BufferedReader data_in = new BufferedReader(new InputStreamReader(sock
				.getInputStream()));
		
		data_out = new PrintWriter(sock.getOutputStream());
		data_out.print("<message MESSAGE='Welcome to the pente server chat room! Type /help for help.' />"+ EOF);
		data_out.flush();

		boolean quit = false;

		// Waits for the EXIT command
		while (!quit) {
			String msg = data_in.readLine();
			
			if (msg == null) {
				quit = true;
			} else if (msg.trim().toUpperCase().equals("/GAMELIST")) {
				SimpleServer.SendGameList(this);
			} else if (msg.trim().toUpperCase().equals("/EXIT")) {
				quit = true;
			} else if (msg.trim().toUpperCase().equals("/HELP")) {
				System.out.println(this.toString() + " asked for help");
				data_out.print("<message MESSAGE='"+ this.toString()+ ", welcome to the server.  There is no help at this time, sorry!' />"+ EOF);
				// TODO make this help useful
				data_out.flush();
			} else {
				SimpleServer.SendMessage(this.game, this, msg.trim());
			}
		}
	}

	public boolean isRunning() {
		return running;
	}

	public PrintWriter getData_out() {
		return data_out;
	}

	@Override
	public String toString() {
		return "Player_" + playerID;
	}

	public Game getGame() {
		return game;
	}

	public void joinGame(Game game) {
		this.game = game;
	}
}